import React , { Component, PropTypes } from "react"
import { connect } from 'react-redux'

import { Paper, TextField, RaisedButton } from 'material-ui';

import * as UserAction from '../../redux/modules/user'

let config = require('config');

class LoginApp extends Component{
  static propTypes={
    user:PropTypes.object.isRequired,
    dispatch:PropTypes.func.isRequired,
  };

  static contextTypes={
    history: PropTypes.object.isRequired
  };

  constructor(props){
    super(props)
  }

  componentDidMount(){
  }

  //在组件接收到一个新的prop时被执行。这个方法在初始化render时不会被调用。
  //旧的props可以通过this.props来获取
  componentWillReceiveProps(nextProps){
    nextProps.isLogin?(window.location.href=config.default.ctx):'';
  }

  doLogin(){
    event.preventDefault();
    const {user,isLogin,dispatch}=this.props;
    const {history}=this.context;

    dispatch(UserAction.login(user));

  }

  getStyles() {
    return {
      main:{
      },
      paper: {
        width:'400px',
        height:'400px',
        marginLeft:'30%',
        marginTop:'100px'
      },
      form: {
        paddingTop:'30px'
      },
      textField: {
        width: '80%',
        paddingLeft:'20px'
      },
      submit: {
        float:'right',

      },
      cancel: {
        float:'right',
        marginLeft:'20px',
        marginRight:'20px'
      }
    };
  }

  render(){
    const styles=this.getStyles();
    const {user,dispatch}=this.props;
    const {history}=this.context;
    return (
      <div style={styles.main}>
        <Paper style={styles.paper} zDepth={2}>
          <form
            style={styles.form}
            onChange={({target})=>{
              dispatch(UserAction.setUser({ [target.name]: target.value }))
            }}
            >
            <TextField
              name='username'
              style={styles.textField}
              hintText='username'
              floatingLabelText='username'
              />
            <TextField
              type="password"
              name='password'
              style={styles.textField}
              hintText='password'
              floatingLabelText='password'
              />
            <RaisedButton
              type='button'
              style={styles.cancel}
              label='Cancel'
              onClick={()=>history.pushState(null, '/login')}
              secondary={true} />

            <RaisedButton
              type='button'
              style={styles.submit}
              label='login'
              onClick={this.doLogin.bind(this)}
              primary />
          </form>
        </Paper>
      </div>
    );
  }
}



//export default AppComponent;
export default connect((state)=>({
  user:state.user.user,
  isLogin:state.user.isLogin,
}))(LoginApp);
